<?php

namespace Fize\Third\XiaoMi\EMI4;

/**
 * 广告触点监测
 * @see https://wtnoyf46ow.feishu.cn/docx/Hlted6zffoDuzaxaym9caGP4nXf
 */
class Feedback
{

    /**
     * 签名
     * @param string $query
     * @param string $secret_key
     * @return string
     */
    public function sign(string $query, string $secret_key): string
    {
        //第一步：将宏参替换为真实值，去掉Feedback URL中的https接口和最后的sign参数
        $query = preg_replace('/&?sign=[^&]*/', '', $query);
        //第二步：在上述参数末尾加上secret_key（该资产上的秘钥），假设为：DktzASwZOnzjBmqV
        $query .= "&secret_key={$secret_key}";
        //第三步：MD5上述参数
        $sign = md5($query);
        //第四步：替换Feedback URL中的SIGN宏参
        return $sign;
    }

    /**
     * 响应
     * @param int    $code
     * @param string $failMsg
     * @param bool   $success
     */
    public function response(int $code, string $failMsg, bool $success)
    {
        $data = [
            "code"    => $code,
            "failMsg" => $failMsg,
            "success" => $success
        ];
        header('Content-Type: application/json; charset=utf-8');
        exit(json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 响应：成功
     * @param string $failMsg
     * @param int    $code
     * @param bool   $success
     */
    public function success(string $failMsg = '', int $code = 0, bool $success = true)
    {
        $this->response($code, $failMsg, $success);
    }

    /**
     * 响应：失败
     * @param string $failMsg
     * @param int    $code
     * @param bool   $success
     */
    public function failure(string $failMsg = '', int $code = 1, bool $success = false)
    {
        $this->response($code, $failMsg, $success);
    }
}